package com.xintool.window.Windows;

import com.xintool.Utils.IconManager;

import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.*;
import java.net.URL;
import java.util.*;
import java.util.List; // 正确导入集合框架的 List
import java.util.Map;  // 确保 Map 也来自 java.util
import java.util.ArrayList; // 如果用到 ArrayList

public class Window_sxkz extends JFrame {
    private static Window_sxkz instance = null;
    private final Map<String, Map<String, Double>> relationMap = new HashMap<>(); // 完整关系表
    private final Map<String, Point> attributePositions = new HashMap<>();
    private String hoveredAttribute = null;
    // 按指定顺序排列的属性列表，用于制图
    private static final String[] ORDERED_ATTRIBUTES = {
            "火", "水", "草", "飞", "电", "地",
            "机械", "冰", "超能", "普通","战斗", "暗影", "光", "龙", "神秘", "圣灵"
    };
    private static double[][] RELATION_MATRIX = new double[16][16]; // 初始化为空矩阵
    private void loadRelationMatrixFromTextFile() {
        try (BufferedReader br = new BufferedReader(new FileReader("data/restraint.txt"))) {
            // 跳过首行标题
            br.readLine();

            int row = 0;
            String line;
            while ((line = br.readLine()) != null && row < 16) {
                // 清洗数据：移除所有非数字、非小数点、非逗号的字符
                String cleaned = line.replaceAll("[^\\d.,]", "");

                // 分割数值字符串
                String[] values = cleaned.split(",");

                // 确保有效数据长度
                if (values.length != 16) continue;

                // 转换为double并填充矩阵
                for (int col = 0; col < 16; col++) {
                    try {
                        RELATION_MATRIX[row][col] = Double.parseDouble(values[col].trim());
                    } catch (NumberFormatException e) {
                        RELATION_MATRIX[row][col] = 1.0; // 默认值
                    }
                }
                row++;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private Window_sxkz() {
        setTitle("属性克制关系图");
        setSize(600, 600);
        setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        setResizable(false);         // 禁止调整窗口大小
        setLocationRelativeTo(null);
        loadRelationMatrixFromTextFile(); // 从文件加载关系矩阵
        initRelations();

        JPanel panel = new JPanel() {
            @Override
            protected void paintComponent(Graphics g) {
                super.paintComponent(g);
                // 先绘制图片
                for (Component comp : getComponents()) {
                    if (comp instanceof JLabel) {
                        comp.paint(g);
                    }
                }
                // 再绘制线条
                drawRelationLines(g);
            }

            private void drawRelationLines(Graphics g) {
                if (hoveredAttribute != null) {
                    Map<String, Double> relations = relationMap.get(hoveredAttribute);
                    if (relations != null) {
                        relations.forEach((target, value) -> {
                            if (value == 2.0) {
                                drawLine(g, hoveredAttribute, target, Color.RED);
                            } else if (value == 0.5) {
                                drawLine(g, target, hoveredAttribute, Color.BLUE);
                            }else if (value == 0) {
                                drawLine(g, hoveredAttribute, target, Color.BLACK);
                            }
                        });
                    }
                }
            }

            private void drawLine(Graphics g, String from, String to, Color color) {
                Point start = attributePositions.get(from);
                Point end = attributePositions.get(to);
                if (start != null && end != null) {
                    Graphics2D g2d = (Graphics2D) g;
                    g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
                    g2d.setColor(color);
                    g2d.setStroke(new BasicStroke(2));
                    g2d.drawLine(start.x, start.y, end.x, end.y);
                }
            }
        };

        panel.setLayout(null);
        panel.setBackground(Color.WHITE);
        add(panel);
        loadAttributeIcons(panel);

        addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosed(WindowEvent e) {
                instance = null;
            }
        });
    }

    private void initRelations() {
        for (int i = 0; i < ORDERED_ATTRIBUTES.length; i++) {
            String attacker = ORDERED_ATTRIBUTES[i];
            Map<String, Double> relations = new HashMap<>();
            for (int j = 0; j < ORDERED_ATTRIBUTES.length; j++) {
                double value = RELATION_MATRIX[i][j];
                if (value != 1) { // 只记录克制关系
                    relations.put(ORDERED_ATTRIBUTES[j], value);
                }
            }
            relationMap.put(attacker, relations);
        }
    }

    private void loadAttributeIcons(JPanel panel) {
        int centerX = 300;  // 窗口中心X
        int centerY = 280;  // 窗口中心Y
        int radius = 220;   // 圆形半径
        int iconSize = 50;  // 图标大小

        // 计算每个属性位置
        double angleStep = Math.PI * 2 / ORDERED_ATTRIBUTES.length;
        double initialAngle = -Math.PI / 2; // 12点方向开始

        for (int i = 0; i < ORDERED_ATTRIBUTES.length; i++) {
            String attribute = ORDERED_ATTRIBUTES[i];

            // 计算位置（极坐标转笛卡尔坐标）
            double angle = initialAngle + angleStep * i;
            int x = (int) (centerX + radius * Math.cos(angle)) - iconSize/2;
            int y = (int) (centerY + radius * Math.sin(angle)) - iconSize/2;

            // 加载图片（使用ClassLoader确保资源路径正确）
            ImageIcon icon = loadImage("static/" + attribute + ".png");

            JLabel label = new JLabel(icon) {
                @Override
                public void paint(Graphics g) {
                    super.paint(g); // 确保图标被绘制
                }
            };

            label.setBounds(x, y, iconSize, iconSize);
            attributePositions.put(attribute, new Point(
                    x + iconSize/2,
                    y + iconSize/2
            ));

            label.addMouseListener(new MouseAdapter() {
                @Override
                public void mouseEntered(MouseEvent e) {
                    hoveredAttribute = attribute;
                    panel.repaint();
                }
                @Override
                public void mouseExited(MouseEvent e) {
                    hoveredAttribute = null;
                    panel.repaint();
                }
            });
            // 将label组件添加到panel容器中
            panel.add(label);
            // 在所有图标加载完成后，为圣灵图标添加白色覆盖
            addWhiteOverlayForShenling(panel);
        }
    }
    private void addWhiteOverlayForShenling(JPanel panel) {
        // 1. 找到圣灵图标的位置
        Point shenlingPos = attributePositions.get("圣灵");
        if (shenlingPos == null) return;

        // 2. 计算白色覆盖层的坐标（与原图标中心对齐）
        int iconSize = 50; // 与图标尺寸一致
        int x = shenlingPos.x - iconSize / 2;
        int y = shenlingPos.y - iconSize / 2;

        // 3. 加载白色图片
        ImageIcon whiteIcon = loadImage("static/blank.png");
        if (whiteIcon == null) return;

        // 4. 创建覆盖层标签（设置为不可触发事件）
        JLabel overlayLabel = new JLabel(whiteIcon) {
            @Override
            public boolean contains(Point p) {
                return false; // 不拦截鼠标事件
            }
        };
        overlayLabel.setBounds(x, y, iconSize, iconSize);
        panel.add(overlayLabel); // 后添加的组件会覆盖在先前的组件上方
    }

    // 修复资源加载方法
    private ImageIcon loadImage(String path) {
        URL resourceUrl = getClass().getClassLoader().getResource(path);
        if (resourceUrl == null) {
            System.err.println("资源未找到: " + path); // 打印错误路径
            return null; // 返回 null 而非空图标
        }
        return new ImageIcon(resourceUrl);
    }

    // 获取窗口实例的静态方法
    public static Window_sxkz getWindow () {
        if (instance == null || !instance.isDisplayable()) {
            instance = new Window_sxkz();
        }
        return instance;
    }

}
